<template>
  <div class="wrap">
    <el-form :model="sendMailForm" size="mini" ref="sendMailForm" >
      <el-form-item label="邮件模板："  :required="true" :show-message="false" class=" mb30">
        <el-select class="w605 mr20 turnBlock f_l" v-model="mailTemplate" filterable  placeholder="选择邮件模板" size="mini" @change="templateSelectMail">
          <el-option v-for="item in mailTemplateList" :key="item.thirdTemplateId" :label="item.templateName" :value="item.id"></el-option>
        </el-select>
        <el-button class="cancelButton mr20 turnBlock f_l" @click="refreshTemplate">刷新</el-button>
      </el-form-item>
      <el-form-item label="邮件标题："  :required="true" :show-message="false" class="mb30">
        <el-input v-model="sendMailForm.mailTitle" placeholder="请输入邮件标题" class="w605" maxlength="50" clearable></el-input>
        <el-tooltip  effect="dark" content="可输入1-50个字符" placement="right">
          <i class="tipsInfo">!</i>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="邮件内容："  :required="true" :show-message="false" class=" mb30 txt">
        <div class="w706 flex mr20 f_l" v-html="mailContent">

        </div>
         <el-button class="searchButton turnBlock f_l" @click="preview()" >预览</el-button>
      </el-form-item>
      <el-form-item label="测试发送：" prop="testReceiver" class="mb60 flex phone labelMarginLeft5">
        <el-input v-model="sendMailForm.testReceiver" placeholder="输入测试邮箱" @change="checkTestMail" maxlength="80" clearable  class="w738 mr20"></el-input>
        <el-button class="searchButton" @click="sendTestMessage">发送</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="编辑"  :visible.sync="editorDialogVisible" width="50%" :before-close="editorDialogClose" center append-to-body :close-on-click-modal="false">
      <el-form :model="mailParamsForm" size="mini" ref="mailParamsForm">
        <el-upload class="avatar-uploader" :action="imgUpload" multiple :on-success="uploadSuccess" :show-file-list="false"></el-upload>
        <el-form-item label="编辑内容：" prop="params"  :required="true" :show-message="false" label-width="100px" style="margin-top: 2px;">
          
          <quill-editor ref="sendMailEditor" v-model="mailParamsForm.params" style="height: 300px;margin-bottom: 45px;margin-top: 10px;" 
        @change="onEditorChange($event)" :options="editorOption"></quill-editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorDialogVisible = false" class="cancelButton mr60">取 消</el-button>
        <el-button type="primary" @click="confirmParams" class="searchButton">确 定</el-button>
      </span>
    </el-dialog>

    
    <el-dialog title="预览"  :visible.sync="previewDialogVisible" width="50%" :before-close="previewDialogClose" center append-to-body :close-on-click-modal="false">
      <div>
        <h2 style="text-align: center; margin-top: 10px;">{{this.sendMailForm.mailTitle}}</h2>
        <div style="margin: 10px 30px 30px 30px;" v-html="this.previewContent"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false" class="searchButton">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { isEmail } from "@/utils/validate";
var toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
  [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction

  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  ['link', 'image'],
  [{ 'align': [] }],

  ['clean']                                         // remove formatting button
];
// 自动化营销-----发微信消息组件
export default {
  name: "mail",
  components: {
    quillEditor,
  },
  data() {
    return {
      ruleForm: {},
      value: "",
      imgUpload: this.utils.imghost,
      editorOption: {
        theme: 'snow',
        boundary: document.body,
        modules: {
          toolbar: {
            container: toolbarOptions,//工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          },
        },
        placeholder: '请输入参数内容',
        readOnly: false
      }, // 富文本初始化
      editorDialogVisible: false,//富文本初始化
      mailParamsForm:{
        params:'',
        key:'', // 参数名称
      },
      mailTemplate:"",
      mailTemplateList: [],//邮件模版
      sendMailForm:{
          tempId:"",
          mailTitle:"",
          previewContent:"",
          templateName:"",
          params:{
            
          },
          testReceiver:""
      },
      //邮件模版内容
      templateContent: "",
      mailContent: "",
      previewContent:"",
      mailParams:[],
      previewDialogVisible: false,//邮件预览弹窗
    };
  },
  props: {
    id:Number,
    nodeInfo: {
      type: Object,
    },
    journeyId: {
      type: String,
      default: '',
    }
  },

  methods: {
    /**
     * 将编辑的数据回调页面
     */
    saveSendMailData(data) {
      this.$emit("saveSendMailData",data);
    },
    /**
     * 邮件参数弹窗关闭
     */
    editorDialogClose(){
      this.editorDialogVisible = false;
    },
    /**
     * 校验邮箱正确性
     */
    checkTestMail(vue){
      if(!isEmail(vue)){
        this.$message({message:"请输入正确的邮箱", type:"error"});
        this.sendMailForm.testReceiver = "";
        return false;
      }
    },
    /**
     * 测试发送
     */
    sendTestMessage(){
      let that = this;
      this.$refs.sendMailForm.validate(valid => {
        if (valid) {
          if(this.sendMailForm.tempId =="" || this.sendMailForm.tempId == null){
            this.$message({message:"请选择邮件模版输入参数后进行测试发送",type:"error"})
            return false;
          }
          if(this.sendMailForm.mailTitle =="" || this.sendMailForm.mailTitle == null){
            this.$message({message:"请输入邮件标题",type:"error"})
            return false;
          }
          for(var i=0;i<that.mailParams.length;i++){
            var key = that.mailParams[i];
            if(that.sendMailForm.params[key]==null || that.sendMailForm.params[key]=='' ){
              that.$message({ message: "请补全邮件参数", type: "error" });
              return false;
            }
          }
          if(!isEmail(this.sendMailForm.testReceiver)){
            this.sendMailForm.testReceiver = "";
            return false;
          }
          that.sendMailForm.type = 3;
          this.utils.request.sendTestMessage(that.sendMailForm, res => {
            if (res.code == "0000") {
              if(res.data.code == "0"){
                  that.$message({ message: res.data.message, type: "success" });
              }else{
                  that.$message({ message: res.data.message, type: "error" });
              }
            }
          });
        }
      });
    },
    /**
     * 邮件模版选择
     */
    templateSelectMail(val){
        let item = null;
        this.mailTemplateList.forEach(email=>{
          if(val == email.id){
            item = email;
          }
        })
      if(item == null){
          this.$message({
            type:"error",
            message: "模板不存在"
          })
          return false;
      }
      this.sendMailForm.mailTitle = item.templateName;
      this.sendMailForm.templateName = item.templateName;
      this.sendMailForm.tempId = item.thirdTemplateId;
      this.previewContent = item.templateContent;
      this.templateContent = item.templateContent;
      var content = item.templateContent;
      var textList = content.split(/\$\{[^}]+\}/);
      var paramList = content.match(/\$\{[^}]+\}/g);
      this.mailParams = [];
      this.sendMailForm.params = {};
      if(paramList != null ){
        for(var i=0;i<paramList.length;i++){
          this.mailParams.push(paramList[i].replace("${","").replace("}",""));
          this.sendMailForm.params[paramList[i].replace("${","").replace("}","")] = "";
          content= content.replace(paramList[i],'&nbsp;&nbsp;<button class="buttonParm" type="button" onsubmit="return false" id="'+paramList[i].replace("${","").replace("}","")+i+'">编辑</button>&nbsp;&nbsp;');

        }
      }
      this.mailContent = content;
      var mailParamsList = this.mailParams;
      //绑定按钮事件
      var that = this;
      $(document).ready(function(){
          $(function() {
            //jq事件
            for(var i=0;i<mailParamsList.length;i++){
              let j = i;
              let key = mailParamsList[j];
              document.getElementById(key+j).onclick = function(){
                that.editorDialogVisible = true;
                that.mailParamsForm.params = "";
                that.mailParamsForm.key = key;
                that.previewContent = item.templateContent;
                //设置value
                that.mailParamsForm.params = that.sendMailForm.params[key]
              }
            }
          });
      
      })
    },
    onEditorChange({ quill, html, text }) {
      this.detailContent = html;
    },
    /**
     * 富文本图片上传
     */
    uploadSuccess(res, file) {
      // 首先获取富文本编辑器的实例
      let quill = this.$refs.sendMailEditor.quill
      // 上传成功所执行
      if (res.code == "0000" && res.data !== null) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片res为服务器返回的数据
        quill.insertEmbed(length, 'image', res.data.imageUrl)
        // 光标移动至文本末端
        quill.setSelection(length + 1)
      } else {
        this.$message({message:"图片插入失败", type:"error" });
      }
    },
    /**
     * 确认弹窗数据保存——邮件参数
     */
    confirmParams(){
      if(this.mailParamsForm.params == null || this.mailParamsForm.params == '' ){
        this.$message({message:"请输入内容", type:"error" });
        return false;
      }
      var key = this.mailParamsForm.key;
      this.sendMailForm.params[key] = this.mailParamsForm.params;
      this.editorDialogVisible = false;
    },
    /**
     * 邮件预览
     */
    preview(){
      if(this.sendMailForm.tempId =="" || this.sendMailForm.tempId == null){
        this.$message({message:"请选择邮件模版输入参数后预览",type:"error"})
        return false;
      }
      //判断参数是否全部输入
      var booFlag = false;
      for (const key in this.sendMailForm.params) {
        const value = this.sendMailForm.params[key];
        if(value == null ||  value == ''){
            booFlag = true;
            break;
        }
      }
      if(booFlag){
        this.$message({message:"请补充完参数后预览",type:"error"})
        return false;
      }
      //预览数据组装
      var paramList = this.templateContent.match(/\$\{[^}]+\}/g);
      var content = this.previewContent;
      if(paramList != null && paramList.length > 0){
        for(var i=0;i<paramList.length;i++){
          var key = paramList[i].replace("${","").replace("}","");
          content= content.replace(paramList[i],this.sendMailForm.params[key]);
        }
      }
      this.previewContent = content;
      this.previewContent = this.previewContent.replace(/img/g,"img style='width:100%;height:100%'"); 
      this.previewDialogVisible = true;

    },
    /**
     * 邮件预览关闭
     */
    previewDialogClose(){
      this.previewDialogVisible = false;
    },
    /**
     * 保存邮件节点
     */
    getPreview(){
      let that = this;
      if(this.sendMailForm.tempId =="" || this.sendMailForm.tempId == null){
        this.$message({message:"请选择邮件模版",type:"error"})
        return null;
      }
      if(this.sendMailForm.mailTitle =="" || this.sendMailForm.mailTitle == null){
        this.$message({message:"请输入邮件标题",type:"error"})
        return null;
      }
      //判断参数是否全部输入
      if(that.mailParams.length > 0){
        for(var i=0;i<that.mailParams.length;i++){
          var key = that.mailParams[i];
          if(that.sendMailForm.params[key]==null || that.sendMailForm.params[key]=='' ){
            that.$message({ message: "请补全邮件参数", type: "error" });
            return null;
          }
        }
      }
       //预览数据组装
      var paramList = this.templateContent.match(/\$\{[^}]+\}/g);
      var content = this.previewContent;
      for(var i=0;i<paramList.length;i++){
        var key = paramList[i].replace("${","").replace("}","");
        content= content.replace(paramList[i],this.sendMailForm.params[key]);
      }
      this.sendMailForm.previewContent = content;
      return this.sendMailForm;
    },
    /**
     * 查询短信邮件模板
     */
    tTempalteListAll(callbackData){
      //查询邮件
      this.utils.request.tTempalteListAll({status: 1, templateType: 2},res=>{
          if(res.code == '0000'){
            this.mailTemplateList = res.data
          }else{
            this.mailTemplateList = []
          }
          if(callbackData != null){
              let item = null;
              this.mailTemplateList.forEach(mailTemplate=>{
                if(mailTemplate.thirdTemplateId == callbackData.tempId){
                  item = mailTemplate;
                }
              })
              this.mailTemplate = item.id+"";
              // 默认选中
              this.templateSelectMail(item.id);
              this.sendMailForm = callbackData;
          }
      })
    },
    /**
     * 刷新模版
     */
    refreshTemplate(){
      this.tTempalteListAll();
    },
  },

  mounted() {
    this.tTempalteListAll();
  }
};
</script>
<style lang="scss" scoped>
.el-checkbox {
  margin-right: 30px;
}
/deep/ .el-form {
  .txt {
    /deep/ .el-form-item {
      margin-top: 0px;
    }
    .flex {
      line-height: 3;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
    }
    .el-textarea {
      width: auto;
    }
  }
  .phone {
    .el-form-item__content {
      display: flex;
      justify-content: flex-start;
    }
  }
  .buttonParm{
    padding: 0 16px !important;
    border-radius: 4px;
    height: 32px !important;
    line-height: 32px !important;
    font-size: 14px !important;
    background: #FFF;
    border: 1px solid #DCDFE6;
    color: #606266;
    background: #66b1ff;
    border-color: #66b1ff;
    color: #FFF;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    -webkit-transition: .1s;
    transition: .1s;
    font-weight: 500;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px;
  }
}
.wd280 {
  width: 240px !important;
}
.font20{
  font-size: 20px !important;
}
/deep/ .w194{
  width: 194px !important;
  .el-input__inner{
    width: 194px  !important;
  }
}
.noMarginRight{
  margin-right: 0 !important;
}
.labelMarginLeft5{
  /deep/ .el-form-item__label{
    margin-left: 10px;
  }
}
/deep/ .w495{
  width: 495px !important;
  .el-input__inner{
    width:495px !important;
  }
}
/deep/ .w605{
  width: 443px !important;
  .el-input__inner{
    width:443px !important;
  }
}
.noMarginLeft{
  margin-left: 0 !important;
}
/deep/ .copyBtn{
  border: 1px solid #0079DC !important;
  border-radius: 16px !important;
  background-color: #409EFF !important;
  color: #fff !important;
}
.mr10{
  margin-right: 10px !important;
}
.desc{
  color: #c4c4c4;
  font-size: 14px;
}
.w706{
  width: 544px !important;
}
.w738{
  width: 580px !important;
}
</style>

